package com.dqp.cslggroup.Widget;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.widget.RemoteViews;

import com.dqp.cslggroup.R;
import com.dqp.cslggroup.SubjectView.SubjectRepertory;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.CompressedBitmap;
import com.dqp.cslggroup.Util.GetTimeUtil;
import com.dqp.cslggroup.Util.SharedPreferencesUtil;
import com.dqp.cslggroup.Util.TimeTools;
import com.dqp.cslggroup.Util.ToastUtil;
import com.dqp.cslggroup.bean.student;
import com.zhuangfei.timetable.model.ScheduleSupport;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


public class CourseWidget extends AppWidgetProvider {
    private static String listItemClick = "com.dqp.cslggroup.MYAPPWIDGET_LISTVIEW_UPDATE";
    private static String buttonRefresh = "com.dqp.cslggroup.MYAPPWIDGET_BUTTON_UPDATE";

    /**
     * 接收Intent
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        String action = intent.getAction();
        String msg;
        int zhou = TimeTools.course_zhoushu(context);
        int week = TimeTools.week();
        assert action != null;
        if (action.equals(buttonRefresh)) {
            msg = "✌课表更新成功";
            AppWidgetManager mgr = AppWidgetManager.getInstance(context);
            ComponentName cn = new ComponentName(context, CourseWidget.class);
            MyRemoteViewsFactory.toDayScheduleList = ScheduleSupport.getHaveSubjectsWithDay(ScheduleSupport.transform(SubjectRepertory.loadSubjects()), zhou, week);
            mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.widget_list);
            ToastUtil.showToast(msg);
        } else if (action.equals(listItemClick)) {
            ToastUtil.showToast(intent.getStringExtra(listItemClick));
        }
    }


    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
        int count = sumDay();
        int zhou = TimeTools.course_zhoushu(context);
        String xq = TimeTools.xinqi();
        String path = getPath(context);
        Bitmap bitmap;
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.course_widget);
        views.setTextViewText(R.id.course_widget_week, "第" + zhou + "周|" + xq);
        views.setTextViewText(R.id.course_widget_day, "相遇常熟理工的第" + count + "天");
        if (path != null) {
            if (CompressedBitmap.fileExist(path)) {
                bitmap = BitmapFactory.decodeFile(path);
                if (bitmap != null) {
                    bitmap = CompressedBitmap.Compressed(bitmap, 0.5f);
                    views.setImageViewBitmap(R.id.course_widget_bg, bitmap);
                } else {
                    SharedPreferencesUtil.removeSp(context, "coursebg_path");
                }
            } else {
                SharedPreferencesUtil.removeSp(context, "coursebg_path");
            }
        }
        Intent intent = new Intent(context, MyRemoteViewsService.class);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        views.setRemoteAdapter(R.id.widget_list, intent);
        Intent clickIntent = new Intent(context, CourseWidget.class);
        clickIntent.setAction(listItemClick);
        clickIntent.setData(Uri.parse(clickIntent.toUri(Intent.URI_INTENT_SCHEME)));
        PendingIntent pendingIntentTemplate = PendingIntent.getBroadcast(context, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setPendingIntentTemplate(R.id.widget_list, pendingIntentTemplate);
        Intent refreshIntent = new Intent(context, CourseWidget.class);
        refreshIntent.setAction(buttonRefresh);
        PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0, refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.button_refresh, refreshPendingIntent);
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        int count = sumDay();
        int zhou = TimeTools.course_zhoushu(context);
        String xq = TimeTools.xinqi();
        String path = getPath(context);
        Bitmap bitmap;
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.course_widget);
        views.setTextViewText(R.id.course_widget_week, "第" + zhou + "周|" + xq);
        views.setTextViewText(R.id.course_widget_day, "相遇常熟理工的第" + count + "天");
        if (path != null) {
            if (CompressedBitmap.fileExist(path)) {
                bitmap = BitmapFactory.decodeFile(path);
                if (bitmap != null) {
                    bitmap = CompressedBitmap.Compressed(bitmap, 0.5f);
                    views.setImageViewBitmap(R.id.course_widget_bg, bitmap);
                } else {
                    SharedPreferencesUtil.removeSp(context, "coursebg_path");
                }
            } else {
                SharedPreferencesUtil.removeSp(context, "coursebg_path");
            }
        }
        Intent intent = new Intent(context, MyRemoteViewsService.class);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[0]);
        views.setRemoteAdapter(R.id.widget_list, intent);


        Intent clickIntent = new Intent(context, CourseWidget.class);
        clickIntent.setAction(listItemClick);
        clickIntent.setData(Uri.parse(clickIntent.toUri(Intent.URI_INTENT_SCHEME)));
        PendingIntent pendingIntentTemplate = PendingIntent.getBroadcast(context, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setPendingIntentTemplate(R.id.widget_list, pendingIntentTemplate);

        Intent refreshIntent = new Intent(context, CourseWidget.class);
        refreshIntent.setAction(buttonRefresh);
        PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0, refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.button_refresh, refreshPendingIntent);
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created

    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled

    }


    private static int sumDay() {
        String cntDateBeg = null;
        int sumDay = 0;
        List<student> studentList = MyApplication.getDaoInstant().getStudentDao().loadAll();
        if (studentList.size() > 0) {
            String rxnf = studentList.get(0).getRxnf();
            if (rxnf.contains("2016")) {
                cntDateBeg = "2016-09-09";
            } else if (rxnf.contains("2017")) {
                cntDateBeg = "2017-09-09";
            } else if (rxnf.contains("2018")) {
                cntDateBeg = "2018-09-09";
            } else if (rxnf.contains("2019")) {
                cntDateBeg = "2019-09-02";
            }
            Date d = new Date();
            @SuppressLint("SimpleDateFormat") DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String cntDateEnd = df.format(d);
            assert cntDateBeg != null;
            sumDay = GetTimeUtil.addDates(cntDateBeg, cntDateEnd);
        }
        return sumDay;
    }

    public static String getPath(Context context) {
        SharedPreferences sp;
        SharedPreferences.Editor editor;
        String path;
        sp = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
        editor = sp.edit();
        path = SharedPreferencesUtil.getStringSp(context, "coursebg_path", null);
        editor.apply();
        return path;
    }

}

